package hu.test.atacama;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Scanner;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

import com.google.gson.Gson;

public class CommService extends IntentService {
	Handler mMainThreadHandler = null;

	public static final String COMMSERVICE_DONE = "hu.test.atacama.COMMSERVICE_DONE";
	public static final String COMMSERVICE_ERROR = "hu.test.atacama.COMMSERVICE_ERROR";

	public CommService() {
		super(CommService.class.getName());
		mMainThreadHandler = new Handler();
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String startingMessage = intent.getExtras()
				.getString("startingMessage");
		if (startingMessage.length() > 0) {
			toastMessage(startingMessage);
		}

		Intent broadcast = null;		
		Common common = Common.getInstance(getApplicationContext());
		String serverAddress = common.getServerAddress();
//		serverAddress = "http://athis-test.appspot.com/Test";
		DataFromDevice dataFromDevice = (DataFromDevice) intent.getExtras()
				.getParcelable("dataFromDevice");

		// TESZT
//		if (dataFromDevice.command.equals("getPath")) {
//			serverAddress = "http://athis-test.appspot.com/Test";
//		}
		// TESZT
		URL url;
		HttpURLConnection connection;
		int statusCode = 0;
		if (common.isOnline()) {
			try {
				if (common.synchronizeGPS) {
					List<Coordinates> savedCoordinates = common
							.loadSavedLocInfo();
					if (savedCoordinates != null) {
						for (Coordinates coordinates : savedCoordinates) {
							dataFromDevice.addCoordinate(coordinates);
						}
					}
				}

				Gson gson = new Gson();
				String jsonFromDevice = gson.toJson(dataFromDevice);
				String body = jsonFromDevice;

				/*
				url = new URL("http://athis-test.appspot.com/Test");
				connection = (HttpURLConnection) url.openConnection();
				connection.setReadTimeout(50000);
				connection.setConnectTimeout(50000);
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setRequestMethod("POST");
				connection.setFixedLengthStreamingMode(body.getBytes().length);
				connection.setRequestProperty("Content-Type",
						"application/json");
				PrintWriter out_test = new PrintWriter(connection.getOutputStream());
				out_test.print(body);
				out_test.close();
				*/
				
				url = new URL(serverAddress);
				connection = (HttpURLConnection) url.openConnection();
				connection.setReadTimeout(50000);
				connection.setConnectTimeout(50000);
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setRequestMethod("POST");
				connection.setFixedLengthStreamingMode(body.getBytes().length);
				connection.setRequestProperty("Content-Type",
						"application/json");
				PrintWriter out = new PrintWriter(connection.getOutputStream());
				out.print(body);
				out.close();
				statusCode = connection.getResponseCode();

				if ((statusCode == 200) && (common.synchronizeGPS)) {
					if (common.isUnuploadedData()) {
						common.deleteSavedFiles();
					}
				}

				String jsonFromCloud = "";
				Scanner inStream = new Scanner(connection.getInputStream());
				while (inStream.hasNextLine())
					jsonFromCloud += (inStream.nextLine());

				DataFromCloud dataFromCloud = gson.fromJson(jsonFromCloud,
						DataFromCloud.class);

				broadcast = new Intent(COMMSERVICE_DONE);
				// broadcast.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
				// min. API 12
				broadcast.putExtra("dataFromCloud", dataFromCloud);				
				toastMessage(dataFromCloud.getMessage());

				if ((common.synchronizeGPS) && (common.isUnuploadedData())
						&& (!dataFromCloud.isError())) {
					common.deleteSavedFiles();
				}
			} catch (IOException ioex) {
				broadcast = new Intent(COMMSERVICE_ERROR);
				toastMessage("CommService I/O exception: " + ioex.toString());
				stopSelf();
			} finally {
				common.synchronizeGPS = false;
			}
		}
		else {
			broadcast = new Intent(COMMSERVICE_ERROR);
		}
		broadcast.putExtra("statusCode", statusCode);
		broadcast.setPackage(getPackageName());
		CommService.this.sendBroadcast(broadcast);
	}

	private void toastMessage(final String message) {
		mMainThreadHandler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_LONG).show();
			}
		});
	}
}
